import nodemailer from "nodemailer";
import yaml from "js-yaml";
import http from "node:http";
import fs from "node:fs";
import url from "node:url";
const mailInfo = yaml.load(fs.readFileSync("./mail.yaml", "utf-8"));
//初始化邮件服务
const transPort = nodemailer.createTransport({
  service: "qq", //邮箱服务提供商
  host: "smtp.qq.com",
  port: 587, //发送邮件端口 465|587 接收邮件端口 995
  secure: true,
  auth: {
    user: mailInfo.user, //邮箱账号
    pass: mailInfo.pass, //邮箱 授权码 | 密码
  },
});
http
  .createServer((req, res) => {
    const { pathname } = url.parse(req.url);
    const { method } = req;
    if (method === "POST" && pathname === "/send/mail") {
      //发送邮件
      let data = "";
      req.on("data", (chunk) => {
        data += chunk;
      });
      req.on("end", () => {
        const { to, subject, text } = JSON.parse(data);
        transPort.sendMail({
          to,
          from: mailInfo.user,
          subject,
          text,
        });
        res.end("ok");
      });
    }
  })
  .listen(3000, () => {
    console.log("Server running on port 3000");
  });
